package org.boge.sharpdoc.controller;

import com.github.pagehelper.PageInfo;
import org.boge.sharpdoc.config.Settings;
import org.boge.sharpdoc.bean.Administrator;
import org.boge.sharpdoc.bean.Banner;
import org.boge.sharpdoc.bean.LayuiReturnData;
import org.boge.sharpdoc.service.BannerService;
import org.boge.sharpdoc.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping(value = "banner/admin")
public class BannerController {
    @Autowired
    private BannerService bannerService;
    @Autowired
    private Settings settings;
    @Autowired
    private HttpSession session;
    @Autowired
    private DocumentService documentService;

    @PostMapping("getAllBanners")
    @ResponseBody
    public LayuiReturnData getAllBanners(Integer index, Integer pageSize) {
        PageInfo<Banner> pageInfo = bannerService.findAllWithPage(index, pageSize);
        List<Banner> banners = pageInfo.getList();
        for (Banner banner : banners) {
            banner.getDocument().setCommentList(null);
            banner.getDocument().setDocGroup(null);
            banner.getDocument().setUploaduser(null);
            banner.getDocument().setSuffixicon(null);
            banner.getDocument().setAuditor(null);
        }
        return new LayuiReturnData(0, true, "数据查询成功！", (int) pageInfo.getTotal(), banners);
    }

    @PostMapping("addBanner")
    @ResponseBody
    public LayuiReturnData addBanner(MultipartFile file, Integer docid) throws IOException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf('.'));
        String filename = UUID.randomUUID() + suffix;
        File imgFile = new File(settings.getBannersDir(), filename);
        file.transferTo(imgFile);

        if (documentService.findDocById(docid) == null)
            return new LayuiReturnData(0, false, "该文章编号不存在！");
        else {
            Administrator current_administrator = (Administrator) session.getAttribute("current_administrator");
            bannerService.addItem(docid, filename, current_administrator.getAdminid());
            return new LayuiReturnData(0, true, "轮播图添加成功！");
        }
    }

    @PostMapping("changeStatus")
    @ResponseBody
    public LayuiReturnData changeStatus(Integer bannerid, String status) {
        bannerService.updateStatus(bannerid, status);
        return new LayuiReturnData(0, true, "轮播图操作成功！");
    }

    @GetMapping("bannerPage")
    public String bannerPage() {
        return "admin/banner";
    }
}